<template>
  <div class="history-container">
    <van-cell-group>
      <van-cell>
        <div slot="title">历史记录</div>
        <div v-if="deleteStatus" class="delete-text">
          <span @click="onDelHistories">全部删除</span>
          <span @click="deleteStatus = false">完成</span>
        </div>
        <div v-else class="delete-icon">
          <van-icon name="delete" @click="onDelete" />
        </div>
      </van-cell>
      <van-cell v-for="(history, index) in searchHistory" :key="index">
        <div slot="title" @click="$emit('update-text', history)">{{ history }}</div>
        <div>
          <van-icon v-if="deleteStatus" @click="onDelHistory(history, index)" name="close" />
        </div>
      </van-cell>
    </van-cell-group>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { userHistory, delUserHistory } from '@/api/search'
import { getItem, removeItem, setItem } from '@/utils/storage'
export default {
  name: 'searchHistory',
  data () {
    return {
      deleteStatus: false,
      searchHistory: []
    }
  },
  props: {
    searchHistoryLists: {
      type: Array,
      required: true
    }
  },
  computed: {
    ...mapState(['user'])
  },
  methods: {
    // 删除操作
    onDelete () {
      this.deleteStatus = true
    },
    // 删除全部历史记录
    async onDelHistories () {
      // 删除全部历史记录并更新视图
      this.searchHistory = []
      // 数据持久化
      if (this.user) {
        // 用户登录状态, 调用接口从后端删除历史数据
        const res = await delUserHistory()
        console.log(res)
      } else {
        // 用户未登录状态, 直接删除本地存储历史数据
        removeItem('search-history')
      }
    },
    // 删除单个历史记录
    onDelHistory (history, index) {
      // 删除单个历史记录, 并且更新视图
      this.searchHistory.splice(index, 1)
      // 数据持久化
      // 后端无单个删除接口, 只能单个删除本地历史记录
      if (!this.user) {
        setItem('search-history', this.searchHistory)
      }
    },
    async getHistory () {
      // 用户登录状态显示用户搜索历史
      if (this.user) {
        const res = await userHistory()
        this.searchHistory = res.data.data.keywords
      } else {
        // 用户非登录状态, 显示本地搜素历史
        const localHistory = getItem('search-history')
        this.searchHistory = localHistory
      }
    }
  },
  created () {
    this.getHistory()
  }
}
</script>
<style lang="less">
.history-container{
  .delete-text{
    span{
      &:nth-child(1){
        margin-right: 5px;
      }
    }
  }
}
</style>
